package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.StockBill;
import cn.wolfcode.crm.mapper.StockBillMapper;
import cn.wolfcode.crm.mapper.StockMapper;
import cn.wolfcode.crm.domain.Stock;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.qo.StockBillObject;
import cn.wolfcode.crm.service.IStockService;
import cn.wolfcode.crm.qo.PageResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class StockServiceImpl implements IStockService {
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private StockBillMapper stockBillMapper;
    @Override
    public PageResult query(QueryObject qo) {
        Integer rows = stockMapper.selectForCount(qo);
        if (rows == 0) {
            return PageResult.EMPTY_RESULT;
        }
        List<Stock> data = stockMapper.selectForList(qo);
        PageResult result = new PageResult(rows,data);
        return result;
    }

    @Override
    //查询明细
    public PageResult selectItmesById(StockBillObject qo) {
        int rows = stockBillMapper.rows(qo);
        if (rows == 0) {
            return PageResult.EMPTY_RESULT;
        }
        List<StockBill> data = (List<StockBill>) stockBillMapper.queryForList(qo);
        PageResult result = new PageResult(rows,data);
        return result;
    }

    //盘点差异的方法
    @Override
    //盘点功能
    public void updateNewNumber(Stock stock) {
        //如果有盘点差异,存入实际的库存量
        if (stock.getNewnumber().equals(BigDecimal.ZERO)) {
            throw new RuntimeException("已盘点");
        }
        //插入到盘点明细
        StockBill bill = new StockBill();
        bill.setCheckDate(new Date());
        //盘点人
        Employee user = (Employee) SecurityUtils.getSubject().getPrincipal();
        bill.setEmployeeId(user.getId());
        bill.setNewnumber(stock.getNewnumber());
        bill.setNumber(stock.getNumber());
        bill.setProductId(stock.getProductId());
        bill.setBillId(stock.getId());
        bill.setProductname(stock.getProductname());
        stockBillMapper.insert(bill);
        stock.setNumber(stock.getNumber().add(stock.getNewnumber()));
        //盘点过后,差异清零,更新库存信息
        //最近一次盘点时间
        stock.setCheckDate(new Date());
        stock.setNewnumber(BigDecimal.ZERO);

        stockMapper.updateNewNumber(stock);
    }
}
